package it.tcm.TeacherClassMate.action;

import it.tcm.TeacherClassMate.beans.EquationBean;
import it.tcm.TeacherClassMate.beans.OrderRowBean;
import it.tcm.TeacherClassMate.beans.OrderMainBean;
import it.tcm.TeacherClassMate.facade.EquationManageBase;
import it.tcm.TeacherClassMate.facade.OrderMainManageBase;
import it.tcm.TeacherClassMate.facade.OrderRowManageBase;
import it.tcm.TeacherClassMate.form.GeneralForm;
import it.tcm.TeacherClassMate.util.Util;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class AddOrderRowAction extends Action {

	// --------------------------------------------------------- Instance Variables

	// --------------------------------------------------------- Methods


	private Logger logger = Logger.getLogger(this.getClass().getName());
	
	/** 
	 * Method execute
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 * 
	 */

	public ActionForward execute(
		ActionMapping mapping,
		ActionForm form,
		HttpServletRequest request,
		HttpServletResponse response) 
	{		
		 logger.info("ADD ORDER ROW");
		 String ids = request.getParameter("ids");
		 OrderMainBean omb  = (OrderMainBean)request.getSession().getAttribute(Util.ORDER_MAIN_OBJECT);
		 logger.info("ids " + ids);
		 String delimiter = ",";
		 String[] rows = ids.split(delimiter);
		 OrderRowManageBase ormb = new OrderRowManageBase();
		 for (String row : rows) {
			 OrderRowBean orb = new OrderRowBean();
			 orb.setIdOrder(omb.getId());
			 if (row.startsWith(Util.EQUATION_PREFIX)) {
				 orb.setIdTypology(Util.EQUATIONS_TYPOLOGY);
			 }
			 logger.info("row.substring(1, row.length() " + row.substring(1, row.length()));
			 orb.setIdForm(Integer.valueOf(row.substring(1, row.length())));
			 ormb.save(orb);
			
		 }
		 OrderMainManageBase ommb = new OrderMainManageBase();
		 omb = ommb.getOrderMainById(omb.getId());
		 if (omb.getOrderRows() != null) logger.info("omb  size " + omb.getOrderRows().size());
		 request.getSession().setAttribute(Util.ORDER_MAIN_OBJECT,omb);
		 request.setAttribute(Util.FORM_GENERAL, new GeneralForm());
		 EquationManageBase emb = new EquationManageBase();
		 List<EquationBean> equationBeanList = emb.getAll();
		 request.setAttribute("resultList", equationBeanList);
					 
		 return mapping.findForward("mergedatatemplate"); 
		 
	}
	
	
}